package org.leetcode.medium;

import org.junit.Test;

import java.util.Arrays;

public class ThreeSumClosest {
    public int threeSumClosest(int[] nums, int target) {
        Arrays.sort(nums);
        int min = Integer.MAX_VALUE;
        for (int first = 0; first < nums.length; first++) {
            if(first > 0 && nums[first] == nums[first - 1]) {
                continue;
            }
            int second = first + 1;
            int third = nums.length - 1;
            while (second < third) {
                if(third < nums.length - 1 && nums[third] == nums[third + 1]) {
                    third--;
                    continue;
                }
                if(second > first + 1 && nums[second] == nums[second - 1]) {
                    second++;
                    continue;
                }
                int sum = nums[first] + nums[second] + nums[third];
                if(Math.abs(target - sum) <= Math.abs(target - min)){
                    min = sum;
                    if(min == target) return target;
                }
                if(sum > target) {
                    third--;
                } else {
                    second++;
                }


            }
        }
        return min;
    }
    @Test
    public void test() {
        int[] nums = new int[]{1,1,1,0};
        int target = -100;
        System.out.println(threeSumClosest(nums, target));
    }
}
